package com.jingzhi.huimiao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import com.google.gson.Gson;
import com.jingzhi.huimiao.base.BaseActivity;
import com.jingzhi.huimiao.bean.User;
import com.jingzhi.huimiao.bean.User.WrongWord;
import com.jingzhi.huimiao.utils.CanstantUtils;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.HttpUtils;
import com.jingzhi.huimiao.utils.SQLdm;

/**
 * 登录页面
 * 
 * @author cxk
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener,
		PlatformActionListener {

	private static long uid = 0;
	private static final int requestCode = 0;
	private SQLiteDatabase db;

	private static final int MSG_SMSSDK_CALLBACK = 1;
	private static final int MSG_AUTH_CANCEL = 2;
	private static final int MSG_AUTH_ERROR = 3;
	private static final int MSG_AUTH_COMPLETE = 4;

	//
	private ImageView iv_toweixin;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		SQLdm s = new SQLdm();
		db = s.openDatabase(LoginActivity.this);

		// 初始化sharesdk
		ShareSDK.initSDK(this);

		// setContentView(R.layout.activity_login);
		tv_title.setText("登录");
		btn_next.setText("开始旅程");
		et_name.setHint("手机号");
		et_password.setHint("密码");

		iv_toweixin = (ImageView) findViewById(R.id.iv_toweixin);

		iv_toweixin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// //微信登录
				// 测试时，需要打包签名；sample测试时，用项目里面的demokey.keystore
				// 打包签名apk,然后才能产生微信的登录
				Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
				authorize(wechat);
			};

		});
	}

	// 执行授权,获取用户信息
	// 文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
	private void authorize(Platform plat) {

		plat.setPlatformActionListener(this);
		// 关闭SSO授权
		plat.SSOSetting(true);
		plat.showUser(null);
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			// super.handleMessage(msg);
			switch (msg.what) {
			case MSG_AUTH_CANCEL: {
				// 取消授权
				Toast.makeText(LoginActivity.this, "授权操作已取消",
						Toast.LENGTH_SHORT).show();
			}
				break;
			case MSG_AUTH_ERROR: {
				// 授权失败
				Toast.makeText(LoginActivity.this,
						"授权操作遇到错误，请阅读Logcat输出; \n 如微信登录，需要微信客户端",
						Toast.LENGTH_SHORT).show();
			}
				break;
			case MSG_AUTH_COMPLETE: {
				// 授权成功
				Toast.makeText(LoginActivity.this, "授权成功，正在跳转登录操作…",
						Toast.LENGTH_SHORT).show();
				Object[] objs = (Object[]) msg.obj;
				String platform = (String) objs[0];
				HashMap<String, Object> res = (HashMap<String, Object>) objs[1];

				// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
				StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
						.detectDiskReads().detectDiskWrites().detectNetwork()
						.penaltyLog().build());
				StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
						.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
						.penaltyLog().penaltyDeath().build());
				try {
					
					Log.e("TAG---", res.toString());
					
					String retStr = HttpUtils.sendPostObj(
							CanstantUtils.wx_url, res, "utf-8");
					
					jxData(retStr);
					Toast.makeText(LoginActivity.this, res.toString(),
							Toast.LENGTH_SHORT).show();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				break;

			default:
				break;

			}

		}

	};

	@Override
	public void setListener() {
		// 给开始旅程按钮设置监听，进入登录页面
		btn_next.setOnClickListener(this);
		// 给返回键设置监听。重回注册页面
		iv_back.setOnClickListener(this);

	}

	ArrayList<User> users = new ArrayList<User>();
	private Gson gson;
	private String name;
	private String upassword;
	private String uname;
	private Cursor rightcur;
	private int rightcount;
	private long currentRC;
	private static String APP_ID;
	private static String GetCodeRequest;
	private static String GetUserInfo;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_next:

			name = et_name.getText().toString().trim();
			String password = et_password.getText().toString().trim();

			// 用于捕获磁盘访问或者网络访问中与主进程之间交互产生的问题
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().penaltyDeath().build());

			// 查询表中该用户的正确答对的单词数，也就是经验值的五分之一
			rightcur = db.rawQuery("select * from word where word_right=2;",
					null);
			if (rightcur.moveToFirst()) {
				rightcount = rightcur.getCount();
			}
			// 查询sp中存储的经验值
			currentRC = DataStoreUtil.getInt(LoginActivity.this, "experience");
			if (currentRC < (rightcount * 5)) {
				currentRC = (rightcount * 5);
			}

			// 查询生词本中数据
			// wrongcur =
			// db.rawQuery("select * from wrong_word where user_id="+name+"",
			// null);

			// 将用户信息存放在Map中
			Map<String, String> userinfo = new HashMap<String, String>();
			userinfo.put("username", name);
			userinfo.put("password", password);
			userinfo.put("experience", currentRC + "");
			try {
				String retStr = HttpUtils.sendPostRequest(
						CanstantUtils.login_url, userinfo, "utf-8");
				Log.e("TAG------", retStr);
				jxData(retStr);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {

			}

			break;
		case R.id.iv_back:
			startActivity(new Intent(getApplicationContext(),
					RegistActivity.class));
			finish();
			break;

		default:
			break;
		}
	}

	/**
	 * 解析接收到的数据
	 * @param retStr
	 */
	private void jxData(String retStr) {
		Gson gson = new Gson();
		User result = gson.fromJson(retStr, User.class);
		if ("success".equals(result.getFan().toString())) {
			uid = result.getUser().getId();
			uname = result.getUser().getUsername();
			upassword = result.getUser().getPassword();

			// 根据用户ID删除生词本中所有数据
			db.execSQL("delete from wrong_word where user_id=" + uid
					+ ";");
			// 获取生词本信息
			WrongWord[] wrongword = result.getWrongWord();
			for (int i = 0; i < wrongword.length; i++) {
				long wrongwd = wrongword[i].getWordId();
				String insertTime = wrongword[i].getInsertTime();
				String substring = null;
				if (insertTime != null) {
					substring = insertTime.substring(0, 10);
				}
				Log.e("time", insertTime + "");
				// 插入生词本数据
				db.execSQL("insert into wrong_word (user_id,word_id,insert_time) values("
						+ uid
						+ ","
						+ wrongwd
						+ ",'"
						+ substring
						+ "');");
			}

			// 存储用户信息
			DataStoreUtil.putint(LoginActivity.this, "userid", uid);
			DataStoreUtil.put(LoginActivity.this, "username", uname);
			DataStoreUtil
					.put(LoginActivity.this, "userpass", upassword);

			// 存储用户经验值
			DataStoreUtil.putintt(LoginActivity.this, "experience",
					result.getUser().getExperience());
			// 存储打卡天数
			DataStoreUtil.putint(LoginActivity.this, "studytime",
					result.getUser().getTotalDay());

			// Intent intent = new Intent(LoginActivity.this,
			// ChooseRoleActivity.class);
			// intent.putExtra("uid", result.getUser().getId());
			// startActivityForResult(intent, requestCode);
			startActivity(new Intent(LoginActivity.this,
					ChooseRoleActivity.class));
			finish();
		} else {
			Toast.makeText(LoginActivity.this, "用户名或密码错误", 0).show();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (rightcur != null && !rightcur.isClosed()) {
			rightcur.close();
		}
		if (db != null) {
			db.close();
		}

	}

	@Override
	public void onCancel(Platform platform, int action) {
		// TODO Auto-generated method stub
		if (action == Platform.ACTION_USER_INFOR) {
			handler.sendEmptyMessage(MSG_AUTH_CANCEL);
		}
	}

	@Override
	public void onComplete(Platform platform, int action,
			HashMap<String, Object> res) {
		// TODO Auto-generated method stub
		if (action == Platform.ACTION_USER_INFOR) {
			Message msg = new Message();
			msg.what = MSG_AUTH_COMPLETE;
			msg.obj = new Object[] { platform.getName(), res };
			handler.sendMessage(msg);
		}
	}

	@Override
	public void onError(Platform platform, int action, Throwable t) {
		// TODO Auto-generated method stub
		if (action == Platform.ACTION_USER_INFOR) {
			handler.sendEmptyMessage(MSG_AUTH_ERROR);
		}
		t.printStackTrace();
	}

}
